<?php

/**
 *   OPENSHOP 供应商管理
 * 
 *   @link        http://baison.com.cn
 *   @copyright   Baison, Inc.
 *   @package     OpenShop
 *   @version     $Id: supplier.php,v 1.0 2009/07/13 13:36:58 modified $
 *   @author      jiajun <jiajun@baisonmail.com>
 */

define('IN_OS', true);
require(dirname(__FILE__) . '/includes/init.php');

$action = isset($_REQUEST['act']) ? $_REQUEST['act'] : 'list';
$exc  = new exchange($os->table("delivery_station"), $db, 'id', 'region_id');
$exc1 = new exchange($os->table("delivery_staff"), $db, 'user_id', 'delivery_id');

if($_REQUEST['act']=='station_list'){
	
    /* 检查权限 */
    admin_priv('station_list');
    
    $list = get_delivery_station_list();
    assign_query_info();
    
    $guide['level_one']=6;
    $guide['level_two']="delivery_station_list";
    $guide['level_three']="";
    
	$smarty->assign('action_link',  array('text' => '添加配送站', 'href' => 'delivery.php?act=add_station'));     
    
    $smarty->assign('ur_here',      '配送站列表');    
    $smarty->assign('guide',$guide);
    $smarty->assign('full_page',    1);
    $smarty->assign('delivery_station_list',$list['item']);    
    $smarty->assign('filter',       $list['filter']);
    $smarty->assign('page_count',   $list['page_count']); 
    $smarty->assign('record_count', $list['record_count']);
    
    $smarty->display("index.tpl");
    	
}elseif($_REQUEST['act']=='add_station'){
	
    /* 检查权限 */
    admin_priv('add_station');	
    assign_query_info();
    
    $guide['level_one']=6;
    $guide['level_two']="station_add";
    $guide['level_three']="";    
    
    /** 获得配送站管理员列表 **/
    $station_admin_list = get_station_admin_list();
    
    /** 获得一级配送区域列表 **/
	$station_region_list = getRegionL1();
    
	$smarty->assign('action_link',  array('text' => '返回配送站列表', 'href' => 'delivery.php?act=station_list'));     
    
    $smarty->assign('ur_here',      '添加配送站');    
    $smarty->assign('guide',$guide);
    $smarty->assign('act',    'add'); 
    $smarty->assign('station_admin_list',$station_admin_list);
    $smarty->assign('station_region_list',$station_region_list);
    
    $smarty->assign('full_page',    1);
	
    $smarty->display("index.tpl");
    	
}elseif($_REQUEST['act']=='add'){
	
    /* 权限判断 */
    admin_priv('addstation');	

    $region_id_1 = trim($_POST['region_id_1']);
    $region_id_2 = trim($_POST['region_id_2']);    
    $region_id_3 = trim($_POST['region_id_3']);    
    $region_id_4 = trim($_POST['region_id_4']);    
    
    $region_id = $region_id_4;
    
    if ($region_id_4 == 0 && $region_id_3 != 0) {
    	$region_id = $region_id_3;
    }elseif ($region_id_3 == 0 && $region_id_2 != 0){
    	$region_id = $region_id_2;
    }elseif ($region_id_2 == 0 && $region_id_1 != 0){
    	$region_id = $region_id_1;
    }
    
    $station_admin_id = trim($_POST['station_admin_id']);
    $station_name = trim($_POST['station_name']);
    $station_address = trim($_POST['station_address']);
    $in_use = intval(trim($_POST['in_use']));

    $sql = "INSERT INTO ".$os->table('delivery_station')."(region_id, station_admin_id, station_name,station_address,in_use) ".
           "VALUES ('$region_id', '$station_admin_id ', '$station_name', '$station_address', '$in_use')";
    $GLOBALS['db']->query($sql);
    
    /* 清除缓存 */
    clear_cache_files();

    $link[0]['text'] = '继续添加配送站';
    $link[0]['href'] = 'delivery.php?act=add_station';

    $link[1]['text'] = '返回配送站列表';
    $link[1]['href'] = 'delivery.php?act=station_list';

    sys_msg('配送站添加成功！', 0, $link);  	
	
	
}elseif($_REQUEST['act']=='edit_station'){

	/* 检查权限 */
    admin_priv('edit_station');	
    assign_query_info();	
    $guide['level_one']=6;
    $guide['level_two']="station_add";
    $guide['level_three']=""; 

    $station_id = $_REQUEST['id'];
    
    $station_admin_list = get_station_admin_list();
    
    $sql = 'SELECT s.id,s.region_id,s.station_admin_id,s.station_name,s.station_address,s.in_use from ' . $GLOBALS['os']->table('delivery_station') . ' as s where s.id = '.$station_id;
    
    $station = $GLOBALS['db']->GetRow($sql);
    // 获取当前配送站的区域ID
    $region_id = $station['region_id'];
    
    $region_name = getRegionName($region_id);
    
    $region_arr = explode("-", $region_name);
    $regionName = '';
    
    for($i = sizeof($region_arr)-2; $i >= 0; $i--){
       $sign = $i==0?' ':'-';	
       $regionName .= $region_arr[$i].$sign;
    }

	$smarty->assign('action_link',  array('text' => '返回配送站列表', 'href' => 'delivery.php?act=station_list'));     
    
    $smarty->assign('ur_here',      '编辑配送站');
    $smarty->assign('guide',$guide);
    $smarty->assign('act',    'edit'); 
    $smarty->assign('station_admin_list',$station_admin_list); 
    $smarty->assign('regionName',$regionName);
    $smarty->assign('regionid',$region_id);
    $smarty->assign('station',$station);
    $smarty->assign('station_id',$station_id);
    $smarty->assign('full_page',    1);
	
    $smarty->display("index.tpl");    

}elseif($_REQUEST['act']=='edit'){

    /* 权限判断 */
    admin_priv('editstation');

    $station_id = trim($_POST['station_id']);
    $region_id = trim($_POST['regionid']);
    $station_admin_id = trim($_POST['station_admin_id']);
    $station_name = trim($_POST['station_name']);
    $station_address = trim($_POST['station_address']);
    $in_use = intval(trim($_POST['in_use'])); 
    
    $param = "region_id = '$region_id', station_admin_id='$station_admin_id', station_name = '$station_name', station_address='$station_address', in_use = '$in_use'";
    
    if ($exc->edit($param,  $station_id))
    {
        /* 清除缓存 */
        clear_cache_files();

    	$link[1]['text'] = '返回配送站列表';
    	$link[1]['href'] = 'delivery.php?act=station_list';

    	sys_msg('配送站信息编辑成功！', 0, $link);	
    }
    else
    {
        die($GLOBALS['db']->error());
    }
	
}elseif($_REQUEST['act']=='staff_list'){
	
    /* 检查权限 */
    admin_priv('staff_list');
    
    $list = get_delivery_staff_list();
    assign_query_info(); 
    
    $guide['level_one']=6;
    $guide['level_two']="delivery_staff_list";
    $guide['level_three']="";
    
	$smarty->assign('action_link',  array('text' => '添加配送站人员', 'href' => 'delivery.php?act=add_staff'));      

	$smarty->assign('ur_here',      '配送站人员列表');    
    $smarty->assign('guide',$guide);
    $smarty->assign('full_page',    1);
    $smarty->assign('delivery_staff_list',$list['item']);    
    $smarty->assign('filter',       $list['filter']);
    $smarty->assign('page_count',   $list['page_count']); 
    $smarty->assign('record_count', $list['record_count']);    

    
    $smarty->display("index.tpl");
    
}elseif($_REQUEST['act']=='staff_edit'){
	
    /* 检查权限 */
    admin_priv('staff_edit');
    
    $staff_id = $_REQUEST['id'];
    
    $sql = 'SELECT d.user_id,d.delivery_id,d.user_name,d.email,d.cell_phone,d.add_time,d.staff_type from ' . $GLOBALS['os']->table('delivery_staff') . ' as d where d.user_id = '.$staff_id;
    
    $staff = $GLOBALS['db']->GetRow($sql);

    $sql = 'select s.id,s.station_name from '.$GLOBALS['os']->table('delivery_station') . ' as s order by s.id asc';
 	$station_list = $GLOBALS['db']->getAll($sql);
 	
    assign_query_info();
    
    $guide['level_one']=6;
    $guide['level_two']="staff_add";
    $guide['level_three']="";
    
	$smarty->assign('action_link',  array('text' => '返回配送人员列表', 'href' => 'delivery.php?act=staff_list')); 	
    $smarty->assign('ur_here',      '编辑配送站人员');    
    $smarty->assign('guide',$guide);
    $smarty->assign('full_page',    1);
    $smarty->assign('staff',$staff);
    $smarty->assign('station_list',$station_list);     
    $smarty->assign('act',    's_edit');     
    $smarty->assign('staff_id',$staff_id);
	
    $smarty->display("index.tpl");
        
}elseif($_REQUEST['act']=='add_staff'){
	
    /* 检查权限 */
 	admin_priv('add_staff');	

 	$guide['level_one']=6;
    $guide['level_two']="staff_add";
    $guide['level_three']="";
    
    $sql = 'select s.id,s.station_name from '.$GLOBALS['os']->table('delivery_station') . ' as s order by s.station_name asc';
 	$station_list = $GLOBALS['db']->getAll($sql);
    
	$smarty->assign('action_link',  array('text' => '返回配送人员列表', 'href' => 'delivery.php?act=staff_list')); 	
    $smarty->assign('ur_here',      '添加配送人员');    
    $smarty->assign('guide',$guide);
    $smarty->assign('act',    's_add');  
    $smarty->assign('station_list',$station_list);    
    $smarty->assign('full_page',    1); 

    $smarty->display("index.tpl");    
    
}elseif($_REQUEST['act']=='s_add'){
	
    /* 权限判断 */
    admin_priv('addstaff');	

    $delivery_id = trim($_POST['delivery_id']);
    $user_name = trim($_POST['user_name']);
    $email = trim($_POST['email']);
    $cell_phone = trim($_POST['cell_phone']);
    $staff_type = intval(trim($_POST['staff_type']));
	$time = gmtime();
    $sql = "INSERT INTO ".$os->table('delivery_staff')."(delivery_id, user_name, email,cell_phone,staff_type,add_time) ".
           "VALUES ('$delivery_id', '$user_name ', '$email', '$cell_phone', '$staff_type', '$time')";
    $GLOBALS['db']->query($sql);
    
    /* 清除缓存 */
    clear_cache_files();

    $link[0]['text'] = '继续添加配送站人员';
    $link[0]['href'] = 'delivery.php?act=add_staff';

    $link[1]['text'] = '返回配送站人员列表';
    $link[1]['href'] = 'delivery.php?act=staff_list'; 

    sys_msg('配送站人员添加成功！', 0, $link);  	 
      
}elseif($_REQUEST['act']=='s_edit'){
	
    /* 权限判断 */
    admin_priv('editstaff');	

	$user_id = trim($_POST['staff_id']);    
    $delivery_id = trim($_POST['delivery_id']);
    $user_name = trim($_POST['user_name']);
    $email = trim($_POST['email']);
    $cell_phone = trim($_POST['cell_phone']);
    $staff_type = intval(trim($_POST['staff_type']));

    $param = "user_id = '$user_id', delivery_id='$delivery_id', user_name = '$user_name', email='$email', cell_phone = '$cell_phone', staff_type = '$staff_type'";
    
    if ($exc1->edit($param,  $user_id))
    {
        /* 清除缓存 */
        clear_cache_files();

    	$link[1]['text'] = '返回配送站人员列表';
    	$link[1]['href'] = 'delivery.php?act=staff_list'; 

    	sys_msg('配送站人员信息编辑成功！', 0, $link);	
    }
    else
    {
        die($GLOBALS['db']->error());
    } 	   
}elseif ($_REQUEST['act']=='remove_station'){
	
    /* 权限判断 */
    admin_priv('remove_station');	
    $station_id = intval($_GET['id']);

    $sql = "DELETE FROM " .$os->table('delivery_station'). " WHERE id = '$station_id'";
    $res = $db->query($sql);
    
    admin_log('', 'remove', '配送站');

    $url = 'delivery.php?act=station_list';
    os_header("Location: $url\n");
    exit;	   
}elseif ($_REQUEST['act']=='remove_staff'){
	
    /* 权限判断 */
    admin_priv('remove_staff');	
    $staff_id = intval($_GET['id']);

    $sql = "DELETE FROM " .$os->table('delivery_staff'). " WHERE user_id = '$staff_id'";
    $res = $db->query($sql);
    
    admin_log('', 'remove', '配送站人员');

    $url = 'delivery.php?act=staff_list';
    os_header("Location: $url\n");
    exit;	   
}


/** json操作区域 */

if($_REQUEST['act']=='edit_station_name'){
	
    /* 检查权限 */
    check_authz_json('edit_station_name');

    $id = empty($_REQUEST['id']) ? 0 : intval($_REQUEST['id']);
    $station_name = empty($_REQUEST['val']) ? '' : json_str_iconv(trim($_REQUEST['val']));	
    
    /* 检查该配送站名称是否重复 */
    if ($exc->num("station_name", $station_name, $id) != 0)
    {
        make_json_error(sprintf('该配送站名称已经存在!', $station_name));
    }
    else
    {
        if ($exc->edit("station_name = '$station_name'", $id))
        {
            admin_log($station_name, 'edit', 'station_name');
            make_json_result(stripslashes($station_name));
        }
    }    
	
}elseif ($_REQUEST['act']=='edit_station_address'){
	
    /* 检查权限 */
    check_authz_json('edit_station_address');

    $id = empty($_REQUEST['id']) ? 0 : intval($_REQUEST['id']);
    $station_address = empty($_REQUEST['val']) ? '' : json_str_iconv(trim($_REQUEST['val']));	
    
    /* 检查该配送站地址是否重复 */
    if ($exc->num("station_address", $station_address, $id) != 0)
    {
        make_json_error(sprintf('该配送站地址已经存在!', $station_address));
    }
    else
    {
        if ($exc->edit("station_address = '$station_address'", $id))
        {
            admin_log($station_address, 'edit', 'station_address');
            make_json_result(stripslashes($station_address));
        }
    }	
}elseif ($_REQUEST['act']=='toggle_in_use'){
	
    /* 检查权限 */
    check_authz_json('toggle_in_use');

    $id = empty($_POST['id']) ? 0 : intval($_POST['id']);
    $val = intval($_POST['val']);
    
    if ($exc->edit("in_use = '".$val."'", $id))
    {
        clear_cache_files();
        make_json_result(stripslashes($val));
    }

}

/**
 * 编辑配送人员信息
 */
if($_REQUEST['act']=='edit_user_name'){
	
    /* 检查权限 */
    check_authz_json('edit_user_name');

    $id = empty($_REQUEST['id']) ? 0 : intval($_REQUEST['id']);
    $user_name = empty($_REQUEST['val']) ? '' : json_str_iconv(trim($_REQUEST['val']));	
    
    /* 检查该配送人员名称是否重复 */
    if ($exc1->num("user_name", $user_name, $id) != 0)
    {
        make_json_error(sprintf('该配送人员名称已经存在!', $user_name));
    }
    else
    {
        if ($exc1->edit("user_name = '$user_name'", $id))
        {
            admin_log($user_name, 'edit', 'user_name');
            make_json_result(stripslashes($user_name));
        }
    }    
	
}elseif ($_REQUEST['act']=='edit_email'){
	
    /* 检查权限 */
    check_authz_json('edit_email');

    $id = empty($_REQUEST['id']) ? 0 : intval($_REQUEST['id']);
    $email = empty($_REQUEST['val']) ? '' : json_str_iconv(trim($_REQUEST['val']));	
    
    /* 检查该配送人员电邮是否重复 */
    if ($exc1->num("email", $email, $id) != 0)
    {
        make_json_error(sprintf('该配送人员电邮已经存在!', $email));
    }
    else
    {
        if ($exc1->edit("email = '$email'", $id))
        {
            admin_log($email, 'edit', 'email');
            make_json_result(stripslashes($email));
        }
    }	
}elseif ($_REQUEST['act']=='edit_cell_phone'){
	
    /* 检查权限 */
    check_authz_json('edit_cell_phone');

    $id = empty($_REQUEST['id']) ? 0 : intval($_REQUEST['id']);
    $cell_phone = empty($_REQUEST['val']) ? '' : json_str_iconv(trim($_REQUEST['val']));	
    
    /* 检查该配送站地址是否重复 */
    if ($exc1->num("cell_phone", $cell_phone, $id) != 0)
    {
        make_json_error(sprintf('该配送站地址已经存在!', $cell_phone));
    }
    else
    {
        if ($exc1->edit("cell_phone = '$cell_phone'", $id))
        {
            admin_log($cell_phone, 'edit', 'cell_phone');
            make_json_result(stripslashes($cell_phone));
        }
    }
}elseif ($_REQUEST['act']=='batch_remove_staff'){
	
    /* 权限判断 */
    check_authz_json('batch_remove_staff');

    if (!isset($_POST['checkboxes']) || !is_array($_POST['checkboxes']))
    {
        sys_msg('没有选择任何配送站人员', 1);
    }

    $count = 0;
    foreach ($_POST['checkboxes'] AS $key => $id)
    {
        if ($exc1->drop($id))
        {
            $name = $exc1->get_name($id);
            admin_log(addslashes($name),'remove','batch_remove_staff');
            $count++;
        }
    }
    $lnk[] = array('text' => '返回配送站人员列表', 'href' => 'delivery.php?act=staff_list');
    sys_msg(sprintf('您已经成功删除 %d 个配送站人员记录', $count), 0, $lnk);
    
}elseif ($_REQUEST['act']=='batch_remove_station'){
	
    /* 权限判断 */
    check_authz_json('batch_remove_station');

    if (!isset($_POST['checkboxes']) || !is_array($_POST['checkboxes']))
    {
        sys_msg('没有选择任何配送站', 1);
    }

    $count = 0;
    foreach ($_POST['checkboxes'] AS $key => $id)
    {
        if ($exc->drop($id))
        {
            $name = $exc->get_name($id);
            admin_log(addslashes($name),'remove','batch_remove_station');
            // 删除该配送站下的所有员工
            $sql = 'DELETE FROM '.$GLOBALS['os']->table('delivery_staff').' where delivery_id = '.$id;
            $GLOBALS['db']->query($sql);
            $count++;
        }
    }
    $lnk[] = array('text' => '返回配送站列表', 'href' => 'delivery.php?act=station_list');
    sys_msg(sprintf('您已经成功删除 %d 个配送站记录', $count), 0, $lnk);
}

/** json操作结束 **/

/** 配送区域列表选择 **/
if ($_REQUEST['act']=='getRegion'){
	
    check_authz_json('getRegion');

    include_once(ROOT_PATH . 'includes/cls_json.php');

    $id = intval($_GET['id']);
    
    $res = getRegion($id);
    
    if (empty($res))
    {
        $res[0] = array(
            'region_id'   => 0,
            'region_name' => ''
        );
    }

    make_json_result($res);
    
}
/** 配送区域列表选择结束 **/

/**
 * 获取所有配送站信息
 *
 * @access  public
 * @return  array
 */
function get_delivery_station_list()
{
	
    /* 查询条件 */
    $filter['keywords']     = empty($_REQUEST['keywords']) ? 0 : trim($_REQUEST['keywords']);
    if ($_REQUEST['is_ajax'] == 1)
    {
       $filter['keywords'] = json_str_iconv($filter['keywords']);
    }
    $filter['sort_by']      = empty($_REQUEST['sort_by']) ? 'id' : trim($_REQUEST['sort_by']);
    $filter['sort_order']   = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);	
	
    $sql = "SELECT count(*) FROM " .$GLOBALS['os']->table('delivery_station');
    $filter['record_count'] = $GLOBALS['db']->getOne($sql);

    /* 分页大小 */
    $filter = page_and_size($filter);    
    
    $arr = array();	
	
    $sql = 'SELECT s.id,s.region_id,s.station_admin_id,s.station_name,s.station_address,s.in_use from ' . $GLOBALS['os']->table('delivery_station') . ' as s order by s.id asc';
    $res = $GLOBALS['db']->getAll($sql);

    $arr = array('item' => $res, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);    
    
    return $arr;    
}

/**
 * 获取所有配送员信息
 *
 * @access  public
 * @return  array
 */
function get_delivery_staff_list()
{
	
    /* 查询条件 */
    $filter['keywords']     = empty($_REQUEST['keywords']) ? 0 : trim($_REQUEST['keywords']);
    if ($_REQUEST['is_ajax'] == 1)
    {
       $filter['keywords'] = json_str_iconv($filter['keywords']);
    }
    $filter['sort_by']      = empty($_REQUEST['sort_by']) ? 'user_id' : trim($_REQUEST['sort_by']);
    $filter['sort_order']   = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);	
	
    $sql = "SELECT count(*) FROM " .$GLOBALS['os']->table('delivery_staff').' as d join '.$GLOBALS['os']->table('delivery_station').' as s on d.delivery_id = s.id';
    $filter['record_count'] = $GLOBALS['db']->getOne($sql);	
	
    /* 分页大小 */
    $filter = page_and_size($filter);      
    
    $arr = array();

    $sql = 'SELECT d.user_id,s.station_name,d.user_name,d.email,d.cell_phone,d.add_time,d.staff_type from ' . $GLOBALS['os']->table('delivery_staff') . ' as d join '.$GLOBALS['os']->table('delivery_station').' as s on d.delivery_id = s.id order by d.user_id asc';
    $res = $GLOBALS['db']->query($sql);
    
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
      $row['add_time'] = local_date($GLOBALS['_CFG']['time_format'], $row['add_time']);
      $arr[] = $row;
    }
    
    $result = array('item' => $arr, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
    return $result;      
}

/**
 * 获取所有配送站管理员信息
 *
 * @access  public
 * @return  array
 */
function get_station_admin_list(){
	
	$arr = array();
	//TODO 根据什么来决定是配送站管理员 
	$sql = 'SELECT a.user_id,a.user_name from ' . $GLOBALS['os']->table('admin_user') . ' as a';
	
	$res = $GLOBALS['db']->getAll($sql);

	return $res;
}

/**
 * 获取所有一级区域信息
 *
 * @access  public
 * @return  array
 */
function getRegionL1(){
	
	$arr = array();

	$sql = 'SELECT r.region_id,r.region_name from ' . $GLOBALS['os']->table('region') . ' as r where r.parent_id = 0';
	
	$res = $GLOBALS['db']->getAll($sql);

	return $res;
}


/**
 * 获取所有指定区域ID下的子区域信息,
 * 没有子区域,则可以认为是末级也就是第四级区域
 *
 * @access  public
 * @return  array
 */
function getRegion($parent_id){
	
	$arr = array();

	$sql = 'SELECT r.region_id,r.region_name from ' . $GLOBALS['os']->table('region') . ' as r where r.parent_id = '.$parent_id;
	
	$res = $GLOBALS['db']->getAll($sql);

	return $res;	
}

/**
 * 递归获取配送站全称
 */
function getRegionName($region_id,$region_name=''){
	
	$sql = 'SELECT r.region_id,r.parent_id,r.region_name from ' . $GLOBALS['os']->table('region') . ' as r where r.region_id = '.$region_id;
    
	$region = $GLOBALS['db']->GetRow($sql);    
    $region_id = $region['region_id'];
	$parent_id = $region['parent_id'];
	$region_name .= $region['region_name'].'-';
	
	if($parent_id != 0){
		return getRegionName($parent_id,$region_name);
	}else{
		return $region_name; 
	}
}

?>